package top.hkyzf.study.leetcode.array;

import org.junit.Test;

import java.util.Arrays;

/**
 * @author 朱峰
 * @date 2022-2-14 9:40
 */
public class 重塑矩阵_566 {
    public int[][] matrixReshape1(int[][] mat, int r, int c) {
        int m = mat.length, n = mat[0].length;
        if (m * n == r * c) {
            int[][] result = new int[r][c];
            int[] temp = new int[r*c];
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    temp[i * n + j] = mat[i][j];
                }
            }
            for (int i = 0; i < r; i++) {
                for (int j = 0; j < c; j++) {
                    result[i][j] = temp[i * c + j];
                }
            }
            return result;
        } else {
            return mat;
        }
    }

    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int m = nums.length;
        int n = nums[0].length;
        if (m * n != r * c) {
            return nums;
        }

        int[][] ans = new int[r][c];
        for (int i = 0; i < m * n; ++i) {
            ans[i / c][i % c] = nums[i / n][i % n];
        }
        return ans;
    }

    @Test
    public void testMatrixReshape () {
        int[][] mat = {{1,2},{3,4}};
        int r=2, c=4;
        int[][] matrixReshape = matrixReshape(mat, r, c);
        for (int[] ints : matrixReshape) {
            System.out.println(Arrays.toString(ints));
        }
    }
}
